<?php

class AdController extends Controller {

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
	$this->render('view', array(
	    'model' => $this->loadModel($id),
	));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($type = '') {
	if ($type == '') {
	    $this->render('select');
	    app()->end();
	}

	//switch type to bind model
	$params = array();
	$eblast = '';
	switch ($type) {
	    case 'equipment':
		$model = new Equipment();
		break;
	    case 'supply':
		$model = new Supply();
		break;
	    case 'vendor' :
		$model = new Vendor();
		$eblast = new Eblast();
		break;
	    case 'technical' :
		$model = new Technical();
		$eblast = new Eblast();
		break;
	    case 'job' :
		$model = new Job();
		break;
	    case 'resume' :
		$model = new Resume();
		break;
	    default :
		$model = new Equipment();
		break;
	}

	if (r()->isPostRequest) {
	    $result = false;
	    switch ($type) {
		case 'equipment':
		    $result = $this->_registerEquipment($model);
		    break;
		case 'supply':
		    $result = $this->_registerSupply($model);
		    break;
		case 'vendor' :
		    $result = $this->_registerCompanySource($model, $eblast, 'Vendor');
		    break;
		case 'technical' :
		    $result = $this->_registerCompanySource($model, $eblast, 'Technical');
		    break;
		case 'job' :
		    $result = $this->_registerJob($model);
		    break;
		case 'resume' :
		    $model->resume_builder = serialize($_POST['ResumeBuilder']);
		    $result = $this->_registerResume($model);
		    break;
		default :
		    $result = $this->_registerEquipment($model);
		    break;
	    }

	    if ($result) {
		//redirect to update
		$this->redirect(array('index', 'id' => $result));
	    }
	}

	$this->render('create', array(
	    'model' => $model,
	    'eblast' => $eblast,
	    'params' => $params
	));
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerEquipment($model) {
	dump($_POST['Equipment']);
	$image = $model->image;
	$model->attributes = $_POST['Equipment'];
	$model->image = $image;
	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {

	    if ($model->image) {
		deleteFile(UPLOAD_PATH . $model->image);
	    }
	    $model->image = UploadHelper::saveImage($fileHandler);
	}
	if ($model->expireDate != '') {
	    $model->expire_time = strtotime($model->expireDate);
	}

	if ($model->validate()) {
	    if ($model->save()) {
		return $model->ad_id;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerSupply($model) {
	$image = $model->image;
	$model->attributes = $_POST['Supply'];
	$model->image = $image;
	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {

	    if ($model->image) {
		deleteFile(UPLOAD_PATH . $model->image);
	    }
	    $model->image = UploadHelper::saveImage($fileHandler);
	}
	if ($model->expireDate != '') {
	    $model->expire_time = strtotime($model->expireDate);
	}

	if ($model->validate()) {
	    if ($model->save()) {
		return $model->ad_id;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerCompanySource($model, $eblast, $postType, $update = '') {
	$image = $model->image;
	$advertisement = $model->advertisement;
	$model->attributes = $_POST[$postType];
	$model->title = $postType;
	$model->image = $image;
	$model->advertisement = $advertisement;

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {
	    if ($model->image) {
		deleteFile(UPLOAD_PATH . $model->image);
	    }
	    $model->image = UploadHelper::saveImage($fileHandler);
	}
	if (isset($_POST[$postType]['featured'])) {
	    //save advertisement image
	    if (($fileHandler = CUploadedFile::getInstance($model, 'advertisement'))) {
		if ($model->advertisement) {
		    deleteFile(UPLOAD_PATH . 'feature/' . $model->advertisement);
		}
		$model->advertisement = UploadHelper::saveImage($fileHandler, 'feature');
	    }
	}

	if ($model->expireDate != '') {
	    $model->expire_time = strtotime($model->expireDate);
	}
	if ($model->validate()) {
	    $flag = true;
	    //eblast validate
	    if (isset($_POST['eblast'])) {
		if (!$update) {
		    $eblast->attributes = $_POST['Eblast'];

		    if (!$eblast->validate()) {
			$flag = false;
		    } else {
//		    if (strtotime($_POST['Eblast']['start_date']) < strtotime('+5 days')) {
//
//			$error = 1;
//			Yii::app()->user->setFlash('eblastTimeError', '<div class="alert alert-block alert-error"><strong>Eblast Error: </strong>
//			    Please pick date after ' . date('d-m-Y', strtotime('+5 days')) . '. This will give us the opportunity to check the ad before we send it.</div>');
//		    } else {
			$aEblast = $_POST['Eblast'];
			if (($fileHandler = CUploadedFile::getInstance($eblast, 'advertisement'))) {
			    $aEblast['advertisement'] = UploadHelper::saveDocument($fileHandler, 'eblast');
			}

			$model->eblast = $aEblast;
		    }
		    //eblast validate
		} else {
		    if (!$eblast) {
			$eblast = new Eblast();
		    }
		    if (isset($_POST['Eblast'])) {
			$eblastFile = $eblast->advertisement;
			$eblast->attributes = $_POST['Eblast'];
			$eblast->advertisement = $eblastFile;
			$eblast->start_date = date("Y-m-d", strtotime($_POST['Eblast']['start_date']));
			//save eblast
			if (($fileHandler = CUploadedFile::getInstance($eblast, 'advertisement'))) {
			    if ($eblast->advertisement) {
				deleteFile(UPLOAD_PATH . 'eblast/' . $eblast->advertisement);
			    }
			    $eblast->advertisement = UploadHelper::saveDocument($fileHandler, 'eblast');
			}
			if (!$eblast->validate()) {
			    $flag = false;
			} else {
			    $eblast->save();
			}
		    }
		}
	    }
	    if ($model->save()) {
		return $model->ad_id;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerJob($model) {
	$model->attributes = $_POST['Job'];
	$model->title = 'Job';

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'resume'))) {
	    $model->image = UploadHelper::saveDocument($fileHandler);
	}
	if ($model->expireDate != '') {
	    $model->expire_time = strtotime($model->expireDate);
	}
	if ($model->validate()) {
	    if ($model->save()) {
		return 10;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerResume($model) {
	$model->attributes = $_POST['Resume'];
	$model->title = 'Resume';

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'resume'))) {
	    $model->image = UploadHelper::saveDocument($fileHandler);
	}
	if ($model->expireDate != '') {
	    $model->expire_time = strtotime($model->expireDate);
	}
	if ($model->validate()) {
	    if ($model->save()) {
		return 10;
	    }
	}

	return false;
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
	$update = 1;
	$model = $this->loadModel($id);
	$eblast = '';
	// Uncomment the following line if AJAX validation is needed
	$this->performAjaxValidation($model);

	if (r()->isPostRequest) {
	    $result = false;
	    switch ($model->type) {
		case Ad::TYPE_EQUIPMENT:
		    $result = $this->_registerEquipment($model);
		    break;
		case Ad::TYPE_SUPPLY:
		    $result = $this->_registerSupply($model);
		    break;
		case Ad::TYPE_VENDOR:
		    $eblast = Eblast::model()->find('ad_id=' . $model->ad_id);
		    $result = $this->_registerCompanySource($model, $eblast, 'Vendor', $update);
		    break;
		case Ad::TYPE_TECHNICAL:
		    $eblast = Eblast::model()->find('ad_id=' . $model->ad_id);
		    $result = $this->_registerCompanySource($model, $eblast, 'Technical', $update);
		    break;
		case Ad::TYPE_RESUME:
		    $model->resume_builder = serialize($_POST['ResumeBuilder']);
		    $result = $this->_registerResume($model);
		    break;
		case Ad::TYPE_JOB :
		    $result = $this->_registerJob($model);
		    break;

		default :
		    $result = $this->_registerEquipment($model);
		    break;
	    }

	    if ($result) {
		//redirect to update
		//$this->redirect(array('update', 'id' => $result));
	    }
	}

	$aAdditionCats = $model->getAllAdditionCat();

	$this->render('update', array(
	    'model' => $model,
	    'aAdditionCats' => $aAdditionCats,
	    'eblast' => $eblast
	));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
	if (Yii::app()->request->isPostRequest) {
	    // we only allow deletion via POST request
	    $this->loadModel($id)->delete();

	    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
	    if (!isset($_GET['ajax']))
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	else
	    throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
	$model = new Ad('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Ad']))
	    $model->attributes = $_GET['Ad'];

	$this->render('admin', array(
	    'model' => $model,
	));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
	$model = Ad::model()->findByPk($id);
	if ($model === null)
	    throw new CHttpException(404, 'The requested page does not exist.');
	return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
	if (isset($_POST['ajax']) && $_POST['ajax'] === 'advertising-form') {
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}
    }

    /**
     * View all eblast
     */
    public function actionAll_eblast() {
	$model = new Eblast('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET['Eblast']))
	    $model->attributes = $_GET['Eblast'];
	$aObjCat = Category::getList();
	$aCats = array();
	foreach ($aObjCat as $cat) {
	    $aCats[$cat->category_id] = $cat->name;
	}

	$this->render('all_eblast', array(
	    'model' => $model,
	    'aCats' => $aCats
	));
    }

    /*
     * edit eblast
     */

    public function actionUpdate_eblast($id) {
	$this->render('update_eblast');
    }

    /*
     * approve eblast
     */

    public function actionApprove_eblast($id) {
	$model = Eblast::model()->findByPk($id);
	if ($model) {
	    $model->status = Eblast::STATUS_APPROVE;
	    $model->save();
	    $this->redirect(BACKEND_SITE_URL . 'adv/ad/all_eblast');
	}
    }

    /*
     * delete eblast
     */

    public function actionDelete_eblast($id) {
	$model = Eblast::model()->findByPk($id);
	if ($model) {
	    $model->delete();
	}
    }

    /*
     * show all report abuse
     */

    public function actionReport_abuse() {
	$model = new Abuse('search');
	$model->unsetAttributes();
	if (isset($_GET['Abuse'])) {
	    $model->attributes = $_GET['Abuse'];
	}
	/**
	 * get all category
	 */
	$aStAbuse = Yii::app()->db->createCommand('SELECT * FROM {{statement_abuses}}')->queryAll();
	$aStatementAbuse = array();
	foreach ($aStAbuse as $abuse) {
	    $aStatementAbuse[$abuse['text']] = $abuse['text'];
	}

	$this->render('report_abuse', array(
	    'model' => $model,
	    'aStatementAbuse' => $aStatementAbuse
	));
    }

    /*
     * delete  report
     */

    public function actionDeleteReportAbuse() {
	if (isset($_GET['id'])) {
	    $model = Abuse::model()->findByPk(intval($_GET['id']))->delete();
	}
    }

}
